package org.study.springboot.learning.socker;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        PrintWriter pw = null;
        BufferedReader br = null;
        try {
            serverSocket = new ServerSocket(18888);
        } catch (IOException e) {
            System.err.println("Could not connet serverSocket:18888");
            System.exit(1);
        }
        Socket incoming = null;

        while (true) {
            incoming = serverSocket.accept();
            //PrintWriter作为输出流 服务端响应客户端，给客户端返回数据。
            pw = new PrintWriter(incoming.getOutputStream(), true);
            //BufferedReader最为输入流，接受客户端发送来的数据
            br = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
            pw.println("Hello !!! ");
            pw.println("Enter BYE to exit");
            pw.flush();
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                }
                else {
                    pw.println("Echo:" + str);
                    pw.flush();
                    System.out.println("Echo:" + str);
                    if ("BYE".endsWith(str.trim())) {
                        break;
                    }
                }
            }
            pw.close();
            br.close();
            incoming.close();
            serverSocket.close();
        }
    }
}
